package com.gxa.learning.core.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * BaseService的泛型
 * abstract是防止这个类被实例化,创建bean
 *
 * @author YXQ
 * @date 2021/11/10 10:50
 */
@Transactional(rollbackFor = {Throwable.class}, propagation = Propagation.REQUIRED)
public abstract class BaseServiceImpl<T> implements BaseService<T> {
    /**
     * 通用Mapper
     * Mapper中的T:通过BaseService接口声明注入:泛型的依赖注入
     * 当泛型擦除,具体类型出现的时候,依赖类型也随之确定
     * 泛型的依赖注入是Spring4之后才出现得技术
     * 尽可能用@Autowired,@Resource尽量不要出现在泛型得依赖注入上
     */
    @Autowired
    private Mapper<T> mapper;

    @Override
    public T selectById(Serializable id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<T> selectByPage(Integer page, Integer size, T... t) throws IllegalAccessException {
        // 启用分页
        PageHelper.startPage(page, size);

        //
        List<T> list = null;
        // 反射得非空字段作为遍历条件
        if (t.length > 0) {
            // 获取模糊查询得条件
            // 反射获取对象类型
            Class<? extends Object> clazz = t[0].getClass();
            // 创建模糊得example实体类
            Example example = new Example(clazz);
            // 模糊规则
            Example.Criteria criteria = example.createCriteria();
            Field[] declaredFields = clazz.getDeclaredFields();
            Method[] declaredMethods = clazz.getDeclaredMethods();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                String name = declaredField.getName();
                Object o = declaredField.get(t[0]);

                if (o != null) {
                    criteria.orLike(name, "%" + o.toString() + "%");
                }
            }

            list = mapper.selectByExample(example);

        } else {
            list = mapper.selectAll();
        }

        // 得到分页信息
        return PageInfo.of(list);
    }

    /**
     * 根据条件查询
     *
     * @param t 条件
     * @return 返回查询到的集合
     * @throws IllegalAccessException
     */
    @Override
    public PageInfo selectByPageEquals(Integer page, Integer size, T t) throws IllegalAccessException {
        page = page == null ? page = 1 : page;
        size = size == null ? size = 10000 : size;
        //指定分页条件
        PageHelper.startPage(page, size);

        List<T> lists = null;
        if (t != null) {
            //通过Example创建查询条件

            Example example = new Example(t.getClass());
            Example.Criteria criteria = example.createCriteria();
            //获取Class
            Class<?> clazz = t.getClass();
            //反射得到所有的字段数组
            Field[] declaredFields = clazz.getDeclaredFields();
            //遍历
            for (Field declaredField : declaredFields) {
                //暴力反射
                declaredField.setAccessible(true);
                //获取字段名
                String name = declaredField.getName();
                //获取字段值
                Object o = declaredField.get(t);
                //如果不为空则进行查询
                if (o != null) {
                    criteria.andEqualTo(name, o.toString());
                }
            }
            lists = mapper.selectByExample(example);
        } else {
            lists = mapper.selectAll();
        }

        return PageInfo.of(lists);
    }

    @Override
    public List<T> select(T t) {

        return mapper.select(t);
    }

    @Override
    public List<T> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public Integer updateById(T t) {
        // updateByPrimaryKeySelective先判断再删除
        // updateByPrimaryKey直接无脑修改
        return mapper.updateByPrimaryKeySelective(t);
    }

    @Override
    public Integer deleteById(Serializable id) {
        return mapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据多个id批量删除
     *
     * @param ids 一个或多个
     * @return 返回是否成功
     * @throws BusinessException 操作中产生的异常
     */
    @Override
    public Boolean batchDel(List<Long> ids) throws BusinessException {
        if (ids != null) {
            for (Serializable id : ids) {
                System.out.println(id);
                System.out.println("-------------------------");
                int i1 = mapper.deleteByPrimaryKey(id);
                if (i1 <= 0) {
                    throw new BusinessException(ExceptionCode.NO_ID_ERROR);
                }
            }
            return true;
        }
        throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
    }

    @Override
    public T insert(T t) {
        mapper.insertSelective(t);
        return t;
    }


}
